import cv2
import numpy as np

if __name__ == '__main__':
    image = cv2.imread('../data/round.jpg')  # 读取图片
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # 转换为灰质图
    blurred = cv2.GaussianBlur(gray, (9, 9), 0)  # 高斯模糊
    circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=0,
                               maxRadius=0)  # 使用霍夫圆变换检测图片中的圆

    if circles is not None:
        circles = np.round(circles[0, :]).astype("int")
        for (x, y, r) in circles:
            circle_area = np.pi * r ** 2

            cv2.circle(image, (x, y), r, (0, 255, 0), 2)

            mask = np.zeros(gray.shape, dtype="uint8")
            cv2.circle(mask, (x, y), r, 255, -1)
            masked_image = cv2.bitwise_and(image, image, mask=mask)

            black_area = cv2.countNonZero(masked_image)
            white_area = circle_area - black_area

            print(f'black_area is {black_area}')
            print(f'white_area is {white_area}')

    cv2.imshow("圆形检测", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
